import {
	base
} from '../utils/base.js';
// var redis = require('../utils/redis.js')
const app = getApp()


//获取token
async function getToken() {
	if (app.globalData.gettingToken) {
		return
	}
	app.globalData.gettingToken = true
	if (!wx.getStorageSync('openid')) {
		wx.showToast({
			title: '登录信息过期，请重新登录',
			duration: 3000,
		})
		wx.redirectTo({
			url: '/pages/user/login/login',
		})
		return
	}

	return new Promise(function(resolve, reject) {
		base.ajax({
			url: 'user/login',
			data: {
				openid: wx.getStorageSync('openid')
			},
			method: 'get',
			success: function(res) {
				let status = res.code;
				if (status == 200) {
					// redis.put('token', res.data.token, 12*60*60)
					var page = getCurrentPages().pop(); //获取当前页面实例
					if (page == undefined || page == null) return;
					page.onLoad();
					resolve(200)
				} else {
					wx.showToast({
						title: '帐号已被禁用，请联系客服',
						duration: 3000,
					})
					wx.redirectTo({
						url: '/pages/login/login',
					})
				}
				app.globalData.gettingToken = false
			},
			fail: function(res) {
				wx.redirectTo({
					url: '/pages/login/login',
				})
			}
		})
	})
}



function requestPost(url, postData, message, success, fail) {
	var type = 'application/x-www-form-urlencoded'
	// if (url == 'app/release/publishArticleKd' || url == 'app/release/publishArticleWM' || url ==
	// 	'app/release/anonymousRelease' || url == 'pay/createOrder' || url == 'app/release/comment' || url ==
	// 	'app/chat/chatPush' || url == 'app/chat/chatRecordList' || url == 'app/release/registration') {
	// 	type = 'application/json'
	// }
	// if (url == 'app/release/selectLists' || url == 'app/release/cauroselList' || url == 'app/release/cauroselContent' ||
	// 	url == 'app/release/classifyZlList') {

	// }
	// else{
	// 	//判断token是否失效
	// 	if (!wx.getStorageSync('openid')) {
	// 		getToken()
	// 		return
	// 	}
	// }

	if (!wx.getStorageSync('openid')) {
		getToken()
		return
	}

	wx.showNavigationBarLoading()
	if (message != "") {
		wx.showToast({
			title: message,
			mask: true,
			icon: 'loading',
		})
	}
	wx.request({
		url: base.baseUrl + url,
		data: postData,
		header: {
			'content-type': type,
			'token': wx.getStorageSync('token')
		},
		method: 'post',
		success: function(res) {
			wx.hideNavigationBarLoading()
			if (message != "") {
				wx.hideToast()
				wx.hideLoading()
			}
			if (res.statusCode == 200) {
				success(res.data)
				return
			} else {
				// fail('登录信息过期')
				wx.redirectTo({
					url: '/pages/login/login',
				})
			}
		},
		fail: function(res) {
			fail()
		},
		complete: function(res) {
			// wx.hideLoading();
			// complete
			wx.hideNavigationBarLoading() //完成停止加载
			wx.stopPullDownRefresh() //停止下拉刷新
		},
	})
}




function requestGet(url, postData, message, success, fail) {
	// if (url != 'app/release/classifyList' && url != 'app/notice/selectPbList') {

	
	if (!wx.getStorageSync('openid')) {
		getToken()
		return
	}
	//判断token是否失效
	// if (!redis.get('token')) {
	// 	getToken()
	// }
	// }
	wx.showNavigationBarLoading()
	if (message != "") {
		wx.showLoading({
			title: message,
		})
	}
	wx.request({
		url: base.baseUrl + url,
		data: postData,
		header: {
			'Content-Type': 'application/json',
			// 'token': wx.getStorageSync('token')
		},
		method: 'get',
		success: function(res) {
			wx.hideNavigationBarLoading()
			if (message != "") {
				wx.hideLoading()
			}
			if (res.statusCode == 200) {
				success(res.data)
			}
			if (res.statusCode == 401) {
				getToken()
			} else {}
		},
		fail: function(res) {
			fail()
		},
		complete: function(res) {
			wx.hideLoading()
		},
	})
}

function getsttingImage(url, success) {
	if (url) {
		wx.showLoading({
			title: '保存中',
			mask: true
		})
		wx.downloadFile({
			url: url,
			success: function(res) {
				if (res.statusCode == 200) {
					//图片保存到本地
					wx.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function(res) {
							wx.hideLoading()
							wx.showModal({
								title: '提示',
								content: '您的推广海报已存入手机相册，赶快分享给好友吧',
								showCancel: false,
							})
							success(res)
						},
						fail: function(err) {
							if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err
								.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
								// 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
								wx.showModal({
									title: '提示',
									content: '需要您授权保存相册',
									showCancel: false,
									success: modalSuccess => {
										wx.openSetting({
											success(settingdata) {
												if (settingdata.authSetting[
														'scope.writePhotosAlbum'
													]) {
													wx.showModal({
														title: '提示',
														content: '获取权限成功,再次点击图片即可保存',
														showCancel: false,
													})
												} else {
													wx.showModal({
														title: '提示',
														content: '获取权限失败，将无法保存到相册哦~',
														showCancel: false,
													})
												}
											},
											fail(failData) {},
											complete(finishData) {}
										})
									}
								})
							}
						},
						complete(res) {
							wx.hideLoading()
						}
					})
				}

			}
		})
	} else {
		wx.showLoading({
			title: '请稍等',
			mask: true
		})
		setTimeout(() => {
			wx.hideLoading()
		}, 1000)
	}
}

function requestMsg(resolve) {
	wx.requestSubscribeMessage({
		tmplIds: ["Gc99Toz2972UlNAV3Tkt_pbrSyTQSxPWuTuqExpgms4"],
		complete: (res) => {

		},
		success: (res) => {
			// 
			if (res['Gc99Toz2972UlNAV3Tkt_pbrSyTQSxPWuTuqExpgms4'] === 'accept') {

			}
		}
	})
}
module.exports = {
	requestPost: requestPost,
	requestGet: requestGet,
	getsttingImage: getsttingImage,
	requestMsg: requestMsg,
	getToken: getToken
}
